package cn.xyy.system.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import cn.xyy.common.domain.mvc.Page;
import cn.xyy.common.domain.system.auth.Role;
import cn.xyy.common.domain.system.auth.RoleVO;
import cn.xyy.common.utils.StringUtils;
import cn.xyy.jdbc.BaseDao;

/**
 * 角色数据持久层
 * 
 * @author xyy
 *
 */
@Repository
public class RoleDao extends BaseDao {

	public Page<Role> selectPage(RoleVO vo) {
		List<Role> list = super.select(
				getSqlPageHandle().handlerPagingSQL(rolePageSql(vo, 0), vo.getPage(), vo.getLimit()), null, Role.class);
		int count = super.getJdbcTemplate().queryForObject(rolePageSql(vo, 1), null, Integer.class);
		Page<Role> page = new Page<Role>(list, count, vo.getLimit(), vo.getPage());
		return page;
	}

	private String rolePageSql(RoleVO vo, int type) {
		StringBuilder sql = new StringBuilder();
		if (type == 0) {
			sql.append("select role_id as id,name,data_scope as dataScopeType,status,create_time as createTime,creator,description from t_sys_role");
		} else {
			sql.append("select count(*) from t_sys_role");
		}
		sql.append(" where 1=1");

		if (StringUtils.isNotBlank(vo.getName())) {
			sql.append(" and name like '%").append(vo.getName().trim() + "%' ");
		}
		if (type == 0) {
			if (StringUtils.isNotBlank(vo.getSidx())) {
				if ((vo.getSord().trim().equalsIgnoreCase("asc"))) {
					sql.append(" order by " + vo.getSidx().split(" ")[0] + " asc");
				} else {
					sql.append(" order by " + vo.getSidx().split(" ")[0] + " desc");
				}
			} else {
				sql.append(" order by id desc");
			}
		}
		return sql.toString();
	}

	public List<Role> selectByUser(String userId) {
		StringBuilder sql = new StringBuilder();
		sql.append(
				"SELECT r.role_id as id,r.name,r.data_scope as dataScopeType from t_sys_user_role ur INNER JOIN t_sys_role r on ur.role_id=r.role_id ");
		sql.append(" where r.status=1 and  ur.user_id=? ");

		return super.select(sql.toString(), new Object[] { userId }, Role.class);
	}

	public List<String> selectRoleDetp(String roleId) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT dept_id from  t_sys_role_dept  ");
		sql.append(" where  role_id=" + roleId + " ");
		return super.getJdbcTemplate().queryForList(sql.toString(), String.class);
	}

	public int updateState(String id, int state) {
		StringBuilder sql = new StringBuilder();
		sql.append("update t_sys_role set status=? where role_id=?");
		return super.insertOrUpdateOrDelete(sql.toString(), new Object[] { state, id });
	}
}
